package com.jnu.accounthelper.ui.home;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.jnu.accounthelper.EditAccountActivity;
import com.jnu.accounthelper.R;
import com.jnu.accounthelper.databinding.FragmentHomeBinding;
import com.jnu.accounthelper.db.Account;
import com.jnu.accounthelper.db.DBManager;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;

    public static final int RESULT_CODE_ADD_DATA = 996;

    private ArrayList<Account> accounts=new ArrayList<>();
    private ArrayList<Account> new_list=new ArrayList<>();
    private RecyclerView outerRecyclerView;
    private SearchView search;
    private ImageButton fab;
    private TextView total;
    private MyRecyclerViewAdapter adapter;
    private TextView input;
    private TextView output;
    private ArrayList<List<Account>> lists=new ArrayList<>();



    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA){
                if(null==data)return;
                String name=data.getStringExtra("type");
                String n=data.getStringExtra("number");
                String source =data.getStringExtra("source");
                String remark =data.getStringExtra("remark");
                int image=data.getIntExtra("image", R.drawable.other);
                int num=Integer.parseInt(n);
                int position=data.getIntExtra("position",accounts.size());
                Account account=new Account(name,remark,num,image,source);
                adapter.accounts.add(position,account);
                adapter.accounts.get(position).setType(name);
                adapter.accounts.get(position).setNumber(num);
                DBManager.insertToAccount(account);
                adapter.notifyItemInserted(position);
                //更新数据显示
                double sum=DBManager.getSum();
                total.setText(String.valueOf(sum));

                double in=DBManager.getInput();
                input.setText(String.valueOf(in));

                double out=DBManager.getOutput();
                output.setText(String.valueOf(out));

            }
        }
    });
    ActivityResultLauncher<Intent>  launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            if(resultCode== RESULT_CODE_ADD_DATA) {
                if(null==data)return;
                String type=data.getStringExtra("type");
                String n=data.getStringExtra("number");
                String source =data.getStringExtra("source");
                String remark =data.getStringExtra("remark");
                int image=data.getIntExtra("image",R.drawable.other);
                int num=Integer.parseInt(n);
                int position=data.getIntExtra("position",accounts.size());
                adapter.accounts.get(position).setType(type);
                adapter.accounts.get(position).setNumber(num);
                adapter.accounts.get(position).setRemark(remark);
                adapter.accounts.get(position).setSource(source);
                DBManager.UpdateToAccount(type,num,source,remark);
                adapter.notifyItemChanged(position);

                //更新数据显示
                double sum=DBManager.getSum();
                total.setText(String.valueOf(sum));

                double in=DBManager.getInput();
                input.setText(String.valueOf(in));

                double out=DBManager.getOutput();
                output.setText(String.valueOf(out));
            }
        }
    });
    @RequiresApi(api = Build.VERSION_CODES.N)
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();   //获得home的布局对象
        try {
            initData();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        outerRecyclerView = root.findViewById(R.id.recycle_view);
        outerRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        adapter = new HomeFragment.MyRecyclerViewAdapter(accounts);
        outerRecyclerView.setAdapter(adapter);

        //显示净资产
        total=root.findViewById(R.id.total_number);
        double sum=DBManager.getSum();
        total.setText(String.valueOf(sum));
        total.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(HomeFragment.this.getContext(), EditAccountActivity.class);
                intent.putExtra("position",0);
                launcherAdd.launch(intent);
            }
        });
        //显示收入
        input=root.findViewById(R.id.input_number);
        double in=DBManager.getInput();
        input.setText(String.valueOf(in));
        //显示支出
        output=root.findViewById(R.id.output_number);
        double out=DBManager.getOutput();
        output.setText(String.valueOf(out));

        search=root.findViewById(R.id.searchAtHome);
        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if(!query.equals("")){
                    accounts=DBManager.selectByRemark("",query);
                    Collections.reverse(accounts);
                    adapter.accounts=accounts;
                    adapter.notifyDataSetChanged();
                }
                else {
                    try {
                        accounts=DBManager.getAccountList();
                        Collections.reverse(accounts);
                        adapter.accounts=accounts;
                        adapter.notifyDataSetChanged();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if(!newText.equals("")){
                    accounts=DBManager.selectByRemark("",newText);
                    Collections.reverse(accounts);
                    adapter.accounts=accounts;
                    adapter.notifyDataSetChanged();
                }
                else {
                    try {
                        accounts=DBManager.getAccountList();
                        Collections.reverse(accounts);
                        adapter.accounts=accounts;
                        adapter.notifyDataSetChanged();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }

        });

        //添加图标的响应事件
        fab=root.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(HomeFragment.this.getContext(), EditAccountActivity.class);
                intent.putExtra("position",0);
                launcherAdd.launch(intent);
            }
        });

        return root;
    }

    protected void initData() throws ParseException {
        /*Account account=new Account("工资", "",3000,R.drawable.salary,"微信");
        account.setDate("2021年10月29日");
        accounts.add(account);
        account=new Account("吃喝饮食","饮料",-50, R.drawable.food,"支付宝");
        account.setDate("2021年11月28日");
        accounts.add(account);
        account=new Account("日用品","沙发",-600, R.drawable.route,"现金");
        account.setDate("2021年10月29日");
        accounts.add(account);
        account=new Account("娱乐","视频会员",-100, R.drawable.entertainmen,"微信");
        account.setDate("2021年12月03日");
        accounts.add(account);
        account=new Account("工资", "",3000,R.drawable.salary,"微信");
        account.setDate("2021年12月03日");
        accounts.add(account);
        account=new Account("工资", "",3000,R.drawable.salary,"微信");
        account.setDate("2021年11月03日");
        accounts.add(account);
        account=new Account("吃喝饮食","饮料",-50, R.drawable.food,"支付宝");
        account.setDate("2021年10月28日");
        accounts.add(account);*/
        /*DBManager.insertToAccount(new Account("欠债", "",-400,R.drawable.debt,"支付宝"));
        DBManager.insertToAccount(new Account("吃喝饮食","",-500, R.drawable.food,"微信"));*/

        /*Account account=new Account("吃喝饮食","饮料",-50, R.drawable.food,"支付宝");
        account.setDate("2021年11月18日");
        DBManager.insertToAccount(account);
        account=new Account("日用品","沙发",-600, R.drawable.route,"现金");
        account.setDate("2021年11月20日");
        DBManager.insertToAccount(account);
        account=new Account("娱乐","视频会员",-100, R.drawable.entertainmen,"微信");
        account.setDate("2021年12月19日");
        DBManager.insertToAccount(account);
        account=new Account("工资", "",3000,R.drawable.salary,"微信");
        account.setDate("2021年12月19日");
        DBManager.insertToAccount(account);*/

        /*DBManager.insertToAccount(new Account("工资", "",3000,R.drawable.salary,"微信"));
        DBManager.insertToAccount(new Account("欠债", "",-400,R.drawable.debt,"支付宝"));
        DBManager.insertToAccount(new Account("吃喝饮食","",-500, R.drawable.food,"微信"));*/
        accounts=DBManager.getAccountList();
        Collections.reverse(accounts);
        /*dataBank=new DataBank(this.getContext());
        accounts=dataBank.loadData();*/
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void devide(){
        Map<String, List<Account>> bmListMap = new HashMap<String, List<Account>>();
        bmListMap = accounts.stream().collect(Collectors.groupingBy(Account -> Account.getDate()));
        for (Map.Entry<String, List<Account>> entry : bmListMap.entrySet()) {
            List<Account> currnrtbmList = entry.getValue();
            lists.add(currnrtbmList);
            int sum=0;
            int image=0;
            String da=new String();
            for (Account account:currnrtbmList) {

                sum+=account.getNumber();
                image=account.getCoverResourceId();
                da=account.getDate();
            }
            Account acc=new Account(entry.getKey(),"",sum,image,"");
            acc.setDate(da);
            new_list.add(acc);
        }
        Collections.reverse(lists);
    }


    /*public class MyOuterRecyclerViewAdapter extends RecyclerView.Adapter{
        private List<Account> accounts;

        public MyOuterRecyclerViewAdapter(List<Account> accounts) {
            this.accounts=accounts;
        }
        @NonNull
        //加载视图
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.prompts, parent, false);
            return new HomeFragment.MyOuterRecyclerViewAdapter.MyViewHolder(view);


        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            HomeFragment.MyOuterRecyclerViewAdapter.MyViewHolder holder =(HomeFragment.MyOuterRecyclerViewAdapter.MyViewHolder)Holder;

            holder.getDate().setText(accounts.get(position).getDate());
            holder.getInput().setText(accounts.get(position).getNumber()+"");
            holder.getOutput().setText(accounts.get(position).getNumber()+"");
            innerList=DBManager.SelectByDay(accounts.get(position).getDate());

            MyRecyclerViewAdapter innerRecyclerViewAdapter;
            innerRecyclerViewAdapter=new MyRecyclerViewAdapter(innerList,holder);
            innerRecyclerViewAdapters.add(innerRecyclerViewAdapter);
            holder.setInnerAdapter(innerRecyclerViewAdapter);
            holder.getInnerRecycler().setAdapter(innerRecyclerViewAdapter);
        }



        @Override
        public int getItemCount() {
            return accounts.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
            public static final int CONTEXT_MENU_ID_ADD = 1;
            public static final int CONTEXT_MENU_ID_EDIT = 2;
            public static final int CONTEXT_MENU_ID_DELETE = 3;

            private final TextView date;
            private final TextView input;
            private final TextView output;
            private final RecyclerView innerRecycler;
            private MyRecyclerViewAdapter innerAdapter;

            private MyViewHolder(View view) {
                super(view);

                this.date=view.findViewById(R.id.date);
                this.input=view.findViewById(R.id.total_input);
                this.output=view.findViewById(R.id.total_output);
                this.innerRecycler = view.findViewById(R.id.inner_recycle_view);
                LinearLayoutManager linearLayoutManager=new LinearLayoutManager(view.getContext());
                linearLayoutManager.setAutoMeasureEnabled(true);
                innerRecycler.setLayoutManager(linearLayoutManager);
                view.setOnClickListener(this);

                innerAdapter = null;
            }

            public MyRecyclerViewAdapter getInnerAdapter() {
                return innerAdapter;
            }

            public void setInnerAdapter(MyRecyclerViewAdapter innerAdapter) {
                this.innerAdapter = innerAdapter;
            }

            public TextView getDate() {
                return date;
            }

            public TextView getInput() {
                return input;
            }

            public TextView getOutput() {
                return output;
            }

            public RecyclerView getInnerRecycler() {
                return innerRecycler;
            }

            @Override
            public void onClick(View v) {
                outPosition=getAdapterPosition();
            }



        }
    }*/

    private class MyRecyclerViewAdapter extends RecyclerView.Adapter{
        private List<Account> accounts;

        public MyRecyclerViewAdapter(List<Account> accounts) {
            this.accounts=accounts;
        }
        @NonNull
        //加载视图
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.account_item_holder, parent, false);
            return new HomeFragment.MyRecyclerViewAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder Holder, int position) {
            HomeFragment.MyRecyclerViewAdapter.MyViewHolder holder =(HomeFragment.MyRecyclerViewAdapter.MyViewHolder)Holder;
            int id =accounts.get(position).getCoverResourceId();
            holder.getImageView().setImageResource(id);
            holder.getType().setText(accounts.get(position).getType());
            holder.getNumber().setText(accounts.get(position).getNumber()+"");
            holder.getRemark().setText(accounts.get(position).getRemark());
            holder.getDate().setText(accounts.get(position).getDate());
        }



        @Override
        public int getItemCount() {
            return accounts.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener, View.OnClickListener {
            public static final int CONTEXT_MENU_ID_ADD = 1;
            public static final int CONTEXT_MENU_ID_EDIT = 2;
            public static final int CONTEXT_MENU_ID_DELETE = 3;
            private final ImageView imageView;
            private final TextView type;
            private final TextView remark;
            private final TextView number;
            private final TextView date;


            public MyViewHolder(View view) {
                super(view);

                this.imageView=view.findViewById(R.id.image_view_book_cover);
                this.type=view.findViewById(R.id.type);
                this.remark=view.findViewById(R.id.remark);
                this.number=view.findViewById(R.id.number);
                this.date =view.findViewById(R.id.item_date);
                view.setOnClickListener(this);
                view.setOnCreateContextMenuListener(this);

            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getType() {
                return type;
            }

            public TextView getRemark() {
                return remark;
            }

            public TextView getNumber() {
                return number;
            }

            public TextView getDate() {
                return date;
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                MenuItem addItem=menu.add(Menu.NONE,CONTEXT_MENU_ID_ADD,CONTEXT_MENU_ID_ADD,"新建");
                MenuItem editItem=menu.add(Menu.NONE,CONTEXT_MENU_ID_EDIT,CONTEXT_MENU_ID_EDIT, "修改");
                MenuItem deleteItem =menu.add(Menu.NONE,CONTEXT_MENU_ID_DELETE,CONTEXT_MENU_ID_DELETE,"删除");
                addItem.setOnMenuItemClickListener(this);
                editItem.setOnMenuItemClickListener(this);
                deleteItem.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int position = getAdapterPosition();
                LayoutInflater li = LayoutInflater.from(HomeFragment.this.getContext());
                View promptsView = li.inflate(R.layout.input_item, null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        HomeFragment.this.getContext());

                alertDialogBuilder.setView(promptsView);
                AlertDialog alertDialog;

                Intent intent;
                switch(item.getItemId())
                {

                    case CONTEXT_MENU_ID_ADD:
                        intent=new Intent(HomeFragment.this.getContext(), EditAccountActivity.class);

                        intent.putExtra("position",position);
                        launcherAdd.launch(intent);

                        break;
                    case CONTEXT_MENU_ID_EDIT:
                        intent=new Intent(HomeFragment.this.getContext(), EditAccountActivity.class);

                        intent.putExtra("position",position);
                        intent.putExtra("name",accounts.get(position).getType());
                        intent.putExtra("number",accounts.get(position).getNumber());
                        intent.putExtra("source",accounts.get(position).getSource());
                        intent.putExtra("remark",accounts.get(position).getRemark());
                        intent.putExtra("image",accounts.get(position).getCoverResourceId());
                        launcherEdit.launch(intent);


                        break;
                    case CONTEXT_MENU_ID_DELETE:
                        View deleteView =li.inflate(R.layout.dialog,null);
                        alertDialogBuilder.setView(deleteView);
                        alertDialogBuilder
                                .setCancelable(false)
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int id) {
                                        Account account=accounts.get(position);
                                        DBManager.deleteAccount(account);
                                        accounts.remove(position);
                                        //dataBank.saveData();
                                        HomeFragment.MyRecyclerViewAdapter.this.notifyItemRemoved(position);
                                    }
                                })
                                .setNegativeButton("Cancel",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog,
                                                                int id) {
                                                dialog.cancel();
                                            }
                                        });

                        // create alert dialog
                        alertDialog= alertDialogBuilder.create();
                        // show it
                        alertDialog.show();

                        break;
                }
                //Toast.makeText(BookListFragment.this.getContext().this,"点击了"+item.getTitle(), Toast.LENGTH_SHORT).show();
                return false;
            }


            @Override
            public void onClick(View v) {
                Intent intent=new Intent(HomeFragment.this.getContext(), EditAccountActivity.class);
                int position=getAdapterPosition();
                intent.putExtra("position",position);
                intent.putExtra("name",accounts.get(position).getType());
                intent.putExtra("number",accounts.get(position).getNumber());
                intent.putExtra("source",accounts.get(position).getSource());
                intent.putExtra("remark",accounts.get(position).getRemark());
                intent.putExtra("image",accounts.get(position).getCoverResourceId());
                launcherEdit.launch(intent);
            }
        }
    }
    @Override
    public void onDestroyView() {

        super.onDestroyView();
        binding = null;
    }
}